﻿using System;
using System.Collections.Generic;
using System.Text;
using MapReduce;
using MapReduce.Comm;
using System.IO;
using System.Reflection;

namespace MapReduceTest
{
    //My starting point for this sample is:
    //http://www.praeclarum.org/2007/04/naive-implementation-of-mapreduce-in-c.html
    public  class RunMaster
    {
        const String PATH = @"C:\Important\work\MapReduce\RunMaster\";
        const String SLAVES = PATH + "Slaves.xml";
        const String CONFIG = PATH + "Config.xml";


        public static void Main(string[] args)
        {


            SlaveManager.Init("127.0.0.1", 
                            U.DEFAULT_MASTER_PORT, 
                            U.DEFAULT_SLAVE_PORT, 
                            SLAVES, 
                            CONFIG, 
                            delegate()
            {
                try
                {
                    MapReduce.MapReduce mr = new MapReduce.MapReduce();
                    mr.Map = new WordCountMap();
                    mr.Reduce = new WordCountReduce();

                    mr.SuccessCallback = ProcessComplete;
                    mr.ErrorCallback = ProcessError;

                    List<KeyValuePair<String, String>> files = GetFiles();
                    uint len = (uint)files.Count;

                    mr.Process(files, len);
                }
                catch (Exception ex)
                {
                    U.Log(ex);
                }
            });


            Console.ReadKey();

        }//Main


        public static void ProcessError(String pMessage)
        {
            U.Log(pMessage);
        }

        public static void ProcessComplete(IEnumerable<KeyValuePair<String, String>> pData)
        {
            U.Log(pData);
        }
















        private static List<KeyValuePair<String, String>> GetFiles()
        {
            String path = PATH+@"TestFiles\";
            string searchPattern = "*.txt";

            List<KeyValuePair<String, String>> op = new List<KeyValuePair<string, string>>();
            foreach (string fileName in Directory.GetFiles(path, searchPattern))
            {
                op.Add(new KeyValuePair<string, string>(fileName, File.ReadAllText(fileName)));
            }
            return op;
        }//GetFiles
    }
}
